var tokenManager = require('../config/token_manager');
var db = require('../config/mongo_database');
var md5 = require('md5');
var redisClient = require('../config/redis_database').redisClient;
var logger = require('../config/log4js').logger('access');
var co = require('co');
var OSS = require('ali-oss');
var fs = require('fs');
var path = require("path");
var moment = require('moment');

var client = new OSS({
  region: 'oss-cn-hongkong-internal',//'oss-cn-shanghai', //'oss-cn-hongkong-internal.aliyuncs.com',
  accessKeyId: 'LTAIQPDVc8QAyZ9A',
  accessKeySecret: 'Dosawap8iXK7yc2mLJev5qcpctKbmV',
  bucket: 'bugunaio'//'bgn' //
});



/*************************
  如何安全下载源码 get请求
  1. 通过订单号和用户ID查询商品ID，
  2. 通过商品ID获取下载地址
  3. 返回下载地址

**************************/
// 获取商品下载链接
exports.download = function(req, res){
	var orderid = req.query.orderid || ''
	logger.info('orderid', orderid)
	// getFile('test/codecanyon-1937522.zip' ,res)
	var userid  = tokenManager.getUserId(req);
	db.orderModel.findOne({orderid:orderid, userid:userid}, function (err, order) {
		logger.error(err);
		if(err || null==order)
			return res.sendStatus(403);
		db.postModel.findOne({pid:order.pid}, function(err, post){
			logger.info(post.download)
			if(post){
				if(post.download=='' || post.download==null)
					return res.sendStatus(405);
				order.times++;
				db.orderModel.update({orderid:orderid, userid:userid}, {$set:{times:order.times, updated:new Date()}}, function(err){
					logger.info("支付成功更新商品下载次数[download]：",orderid, err)
				})
				var key = md5(order.pid + moment(new Date()).format("mmssSS"))
				redisClient.set(key, post.download);
            	redisClient.expire(key, 300);
            	return res.json({key:key})
			}
		})
	})
}

exports.getfile= function(req, res) {
	var key = req.query.key || ''
	redisClient.get(key, function(err, fileName) {
		logger.info('getfile', fileName)
		if(err || fileName==null || fileName=='') return res.end(404);
		co(function* () {
		  	var result = yield client.getStream(fileName);
		 	res.attachment(fileName);
		  	result.stream.pipe(res);
		}).catch(function (err) {
	  		logger.error('[download]:',err)
	  		res.end(404);
		});

	});
}

exports.test= function(req, res) {
	// var fileName = 'y0728002/bazaar.zip';
	var fileName = '0.png'
	co(function* () {
	  	var result = yield client.getStream(fileName);
	 	res.attachment(fileName);
	  	result.stream.pipe(res);
	}).catch(function (err) {
  		res.end(404);
	});
}